package com.zhangbo.myapplication.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.zhangbo.myapplication.constant.ConstantString;

public class MessengerService extends Service {
    private static final String Tag = MessengerService.class.getSimpleName();

    private static class MessageHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ConstantString.MSG_FROM_CLINT:
                    Log.e(Tag, "receive msg from client: " + msg.getData().getString("msg"));
                    Messenger messenger = msg.replyTo;
                    Message message = Message.obtain(null, ConstantString.MSG_FROM_SERVICE);
                    Bundle bundle = new Bundle();
                    bundle.putString("replay", "嗯, 你的消息我已经收到, 稍后回复给你.");
                    message.setData(bundle);
                    try {
                        messenger.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    private final Messenger messenger = new Messenger(new MessageHandler());

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(Tag, "onBind.");
        return messenger.getBinder();
    }


    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(Tag, "onCreate.");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(Tag, "onDestroy.");
    }
}
